<template>
  <div class="salesanalysis-list">
    <Row type='flex'
         justify="space-between"
         class="coinrevenue-list-edit">
      <Row type='flex'
           align='middle'>
        <Col>
        <span class="concrete-data">时间：</span>
        <datePickerYmd @on-change="search"
                       :selectDateType.sync='selectDateType'
                       :dataType='dataType'
                       :dateOption="dateOption"
                       v-model="timeDate"
                       style="display:inline-block"></datePickerYmd>
        </Col>
        <Row type='flex'
             align='middle'
             class="export-btn">
          <Col><span>门店名称：</span></Col>
          <Col>
          <vueTreeselectChoice :multiple="true"
                               ref="vueTreeselectChoice"
                               @input="handleShop"
                               @on-api-finish="apiFinish"
                               permissionCode="moms:report:gamecouponrevenueanalytics"
                               v-model="ShopValue"></vueTreeselectChoice>
          </Col>
          <Col>
          <Button type="primary"
                  class="coinrevenue-btn export-btn"
                  style="width:80px;"
                  @click="search">查询</Button>
          </Col>
        </Row>
      </Row>
      <Col class="export_receivable" v-if="hasPermission('moms:report:membersvipanalyticsexport')">
              <Button class="check_all"
              @click="DropdownItemn('svipAnalysisDetail')"
                style="width:80px">导出
              </Button>
      </Col>
    </Row>
    <Table ref="rowSpanTable"
           stripe
           border
           :height="tableHeight"
           :loading='loading'
           class="table-list"
           :columns="columns"
           :data="resData">
      <template slot-scope="{ row }"
                slot="svipCount">
        <span class="deposit"
              @click="jumpdetail(row.shopId,row.shopName)">{{row.svipCount}}</span>
      </template>
      <template slot-scope="{ row }"
                slot="repeatSaleCount">
        <span class="deposit"
              @click="jumpbehavior(row.shopId,row.shopName)">{{row.repeatSaleCount}}</span>
      </template>
    </Table>
    <div class="page-box"
         style="margin-top: 20px">
      <Page :total="total"
            ref="pages"
            :current.sync="searchObj.offset"
            :page-size="searchObj.limit"
            @on-change="handlePage"
            @on-page-size-change="handlePageSize"
            show-sizer
            :page-size-opts="$pageSizeOpts"
            show-total />
    </div>
  <down-center ref="downCenterRef"
            perms="moms:report:membersvipanalyticsexport"
            v-if="hasPermission('moms:report:membersvipanalyticsexport')"></down-center>
  </div>
</template>
<script>
import vueTreeselectChoice from '@/components/vue-treeselect-choice'
import datePickerYmd from '@/components/date-picker-ymd/date-picker-ymd.vue'
import dayjs from 'dayjs'
import DownCenter from '@/view/components/down-center/index.vue'
import { svipSanalysisList } from '@/api/report/svip'
import { mapState } from 'vuex'
export default {
  name: 'report_member_salesanalysis',
  components: { vueTreeselectChoice, datePickerYmd, DownCenter },
  data () {
    return {
      dataType: [{ key: 'date', value: '日' }, { key: 'month', value: '月' }, { key: 'year', value: '年' }],
      selectDateType: 'date',
      total: 0,
      timeDate: [dayjs().subtract(1, 'day').format('YYYY-MM-DD 00:00:00'), dayjs(new Date()).format('YYYY-MM-DD 00:00:00')],
      dateOption: {
        disabledDate: date => {
          if (process.env.NODE_BUILD === 'prod') return dayjs(date).isAfter(dayjs(new Date()).subtract(1, 'day'))
          return dayjs(date).isAfter(dayjs(new Date()))
        }
      },
      ShopValue: [],
      searchObj: {
        shopId: [],
        offset: 1,
        limit: 10
      },
      loading: false,
      resData: [
        {}
      ],
      tableHeight: 0,
      columns: [
        { title: '门店', key: 'shopName', align: 'center', width: 200, fixed: 'left' },
        { title: 'SVIP权益名称', key: 'svipName', align: 'center', width: 200 },
        { title: 'SVIP会员卡销售额', key: 'svipAmount', align: 'center', width: 200 },
        { title: 'SVIP会员卡购买次数', slot: 'svipCount', align: 'center', width: 200 },
        { title: 'SVIP会员卡销售均价', key: 'svipAveragePrice', align: 'center', width: 200 },
        { title: '首次消费订单数', key: 'firstSaleCount', align: 'center', width: 200 },
        { title: '首次消费金额', key: 'firstSaleAmount', align: 'center', width: 200 },
        { title: '会员复购次数', slot: 'repeatSaleCount', align: 'center', width: 200 },
        { title: '会员复购金额', key: 'repeatSaleAmount', align: 'center', width: 200 }
      ]
    }
  },
  computed: {
    ...mapState({
      merchantId: state => state.user.merchantId,
      userId: state => state.user.userId,
      userName: state => state.user.userName
    }),
    startDate () {
      return this.timeDate[0]
    },
    endDate () {
      return this.timeDate[1]
    }
  },
  methods: {
    search () {
      if (!dayjs(this.startDate).isValid()) {
        this.$Message.error(`请选择时间`)
      } else if (!this.searchObj.shopId.length) {
        this.$Message.error(`请选择门店列表`)
      } else {
        this.searchObj.offset = 1
        this.searchObj.limit = 10
        this.getList()
      }
    },
    DropdownItemn (name) {
      if (!this.searchObj.shopId.length) return this.$Message.error(`请选择门店列表`)
      this.$refs.downCenterRef.addTask({
        merchantId: this.$store.state.user.merchantId,
        shopIds: this.searchObj.shopId,
        startDate: this.startDate,
        endDate: this.endDate,
        dateType: { year: 2, month: 1, date: 0 }[this.selectDateType],
        taskModule: name,
        extraMapParam: {
          mobileNumber: ''
        }
      })
    },
    getList () {
      this.loading = true
      this.tableHeight = 0
      svipSanalysisList({
        merchantId: this.merchantId,
        shopIds: this.searchObj.shopId,
        // shopIds: ['aaae3be8-0323-4208-b903-638d4d8949c5'],
        startDate: this.startDate,
        endDate: this.endDate,
        offset: (this.searchObj.offset - 1) * this.searchObj.limit,
        limit: this.searchObj.limit
      }).then(res => {
        this.loading = false
        if (res.data.status === 200) {
          this.total = res.data.totalCount
          if (res.data.data && res.data.data.length >= 14) {
            this.tableHeight = 520
          }
          this.resData = res.data.data ? res.data.data : []
        } else {
          this.$Message.error(`${res.data.error}`)
        }
      })
    },
    // 获取页码
    handlePage (val) {
      this.searchObj.offset = val
      this.getList()
    },
    handlePageSize (pageSize) {
      this.searchObj.limit = pageSize
      this.getList()
    },
    jumpdetail (idx, name) {
      if (!dayjs(this.startDate).isValid()) {
        this.$Message.error(`请选择时间`)
      } else if (!this.searchObj.shopId.length) {
        this.$Message.error(`请选择门店列表`)
      } else {
        this.$router.push({
          name: 'report_member_salesanalysis_detail',
          query: { id: [idx], type: this.selectDateType, timeDate: this.timeDate, selectDateType: this.selectDateType, shopName: name }
        })
      }
      // this.$router.push({ name: 'report_member_salesanalysis_detail', params: { id: 1 } })
    },
    jumpbehavior (idx, name) {
      if (!dayjs(this.startDate).isValid()) {
        this.$Message.error(`请选择时间`)
      } else if (!this.searchObj.shopId.length) {
        this.$Message.error(`请选择门店列表`)
      } else {
        this.$router.push({ name: 'report_member_salesanalysis_behavior_detail', query: { id: [idx], type: this.selectDateType, timeDate: this.timeDate, selectDateType: this.selectDateType, shopName: name } })
      }
    },
    async handleShop () {
      const ids = await this.$refs.vueTreeselectChoice.getShopId()
      this.searchObj.shopId = ids
      this.search()
    },
    apiFinish () {
      this.ShopValue = null
    }
  }
}
</script>
<style lang="less" scoped>
.deposit {
  cursor: pointer;
  color: #2d8cf0;
  text-decoration: underline rgb(45, 140, 240);
}
.coinrevenue-list-edit {
  padding: 20px;
  // min-width: 1200px;

  .concrete-data {
    margin-left: 10px;
  }

  .common-input {
    width: 180px;
  }

  .vue-treeselect__control {
    height: 32px;
  }

  .coinrevenue-btn {
    width: 80px;
  }

  .coinrevenue-btn2 {
    width: 100px;
  }

  .export-btn {
    margin-left: 24px;
  }

  .marginTop {
    padding-top: 20px;
  }
}
</style>
